package com.example.test.model.social_api;

import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.example.test.activity.FriLineActivity;
import com.example.test.model.Constants;
import com.example.test.model.json_analyzer.NetJsonAnalyzer;
import com.netease.microblog.framework.net.task.CallBackManager;
import com.netease.microblog.framework.net.task.TaskCallBack;
import com.netease.microblog.http.blogapi.NeteaseApi;
import com.tencent.a.b.m;
import com.tencent.weibo.sdk.android.api.TimeLineAPI;
import com.tencent.weibo.sdk.android.api.UserAPI;
import com.tencent.weibo.sdk.android.api.WeiboAPI;
import com.tencent.weibo.sdk.android.api.util.Util;
import com.tencent.weibo.sdk.android.model.AccountModel;
import com.tencent.weibo.sdk.android.model.GlobalVar;
import com.tencent.weibo.sdk.android.model.ModelResult;
import com.tencent.weibo.sdk.android.network.HttpCallback;

public class NetAPI {

	static HashMap<Integer, Handler> handlerMap;
	static HashMap<Integer, Boolean> judgeMap =new HashMap<Integer, Boolean>(10);
	private static TaskCallBack callback = new TaskCallBack(){
		@Override
		public void onFollowed(int id, String data) {
			synchronized (judgeMap.get(id)) {
				
			
			try {
				boolean rs=new JSONObject(data).getJSONObject("source").getBoolean("following");
				judgeMap.put(id, rs);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			judgeMap.get(id).notifyAll();
			}
		}
		@Override
		public void onFollow(int id, String data) {
			if(data.contains("name"))
			{
				Message msg=new Message();
                msg.what=Constants.MSG_FOLLOW_SUCCESS;
                try {
					msg.obj=new JSONObject(data).get("id");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                handlerMap.get(id).sendMessage(msg);
			}
		}
		@Override
		public void onCancelFollow(int id, String data) {
			if(data.contains("name"))
			{
				Message msg=new Message();
                msg.what=Constants.MSG_CANCELFOLLOW_SUCCESS;
                try {
					msg.obj=new JSONObject(data).get("id");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                handlerMap.get(id).sendMessage(msg);
			}
		}
		@Override
		public void onFollowedError(int id, String err) {
			synchronized (judgeMap.get(id)) {
				judgeMap.get(id).notifyAll();
			}
			
		}

		@Override
		public void onGetCommentToMeLine(int id, String data) {
			if(data.equals("[]")) 
				return ;
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{status:"+data+"}","status");
			 for (HashMap<String, String> map : lArrData) {
				 map.put("userscreen_name",map.get("username"));
				 map.put("statususername", map.get("in_reply_to_user_name"));
				 map.put("statustext", map.get("in_reply_to_status_text"));
				 map.put("statusid", map.get("in_reply_to_status_id"));
				 map.put("resource", "netease");
	               if(map.get("source").indexOf("</a>")==-1)
	               {
	            	   map.put("source", "<a>"+map.get("source")+"</a>");
	               }
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETCOMMENT_SUCCESS, lArrData);
		}
		@Override
		public void onGetMentionLine(int id, String data) {
			if(data.equals("[]")) 
				return ;
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{status:"+data+"}","status");
			 for (HashMap<String, String> map : lArrData) {
				 map.put("userscreen_name",map.get("username"));
	               map.put("reposts_count",map.get("retweet_count"));
	               map.put("attitudes_count","0");
	               if(!map.get("root_in_reply_to_status_id").equals("null"))
	               {
	            	   map.put("retweeted_statustext",map.get("root_in_reply_to_status_text"));
	                   map.put("retweeted_statusid",map.get("root_in_reply_to_status_id"));
	                   map.put("retweeted_statususerscreen_name",map.get("root_in_reply_to_user_name"));
	               }
	               if(map.get("source").indexOf("</a>")==-1)
	               {
	            	   map.put("source", "<a>"+map.get("source")+"</a>");
	               }
                  if(map.get("photoUrl")!=null)
	               map.put("images", map.get("photoUrl"));
                  else
               	   map.put("images","");
                  map.put("retweeted_statusimages", "");
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETTIMELINE_SUCCESS, lArrData);
		}
		@Override
		public void onGetOneWeibo(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{status:["+data+"]}","status");
			 for (HashMap<String, String> map : lArrData) {
				 map.put("userscreen_name",map.get("username"));
	               map.put("reposts_count",map.get("retweet_count"));
	               map.put("attitudes_count","0");
	               map.put("images","");
	               if(map.get("source").indexOf("</a>")==-1)
	               {
	            	   map.put("source", "<a>"+map.get("source")+"</a>");
	               }
	               if(!map.get("root_in_reply_to_status_id").equals("null"))
	               {
	            	   map.put("retweeted_statustext",map.get("root_in_reply_to_status_text"));
	                   map.put("retweeted_statusid",map.get("root_in_reply_to_status_id"));
	                   map.put("retweeted_statususerscreen_name",map.get("root_in_reply_to_user_name"));
	               }
	               map.put("retweeted_statusimages", "");
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETONEWEIBO_SUCCESS, lArrData);
		}
		@Override
		public void onGetFollowList(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr(data,"users");
			 for (HashMap<String, String> map : lArrData) {
					map.put("uid", map.get("id"));
					map.put("resource","netease");
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETFOLLOWLIST_SUCCESS, lArrData);
		}
		@Override
		public void onGetFollowers(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr(data,"users");
			 for (HashMap<String, String> map : lArrData) {
					map.put("uid", map.get("id"));
					map.put("resource","netease");
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETFOLLOWERS_SUCCESS, lArrData);
		}
		@Override
		public void onGetUserTimeLine(int id, String data) {
             onGetTimeline(id, data);
		}
		
		@Override
		public void onComment(int id, String data) {
			try {
				sendMsg(handlerMap.get(id), Constants.MSG_COMMENT_SUCCESS, "netease"+new JSONObject(data).getString("in_reply_to_status_id"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void onRepost(int id, String data) {
			
		try {
			sendMsg(handlerMap.get(id), Constants.MSG_REPOST_SUCCESS, "netease"+new JSONObject(data).getJSONObject("retweeted_status").getString("id"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		@Override
		public void onGetUserTimeLineError(int id, String err) {
			// TODO Auto-generated method stub
			super.onGetUserTimeLineError(id, err);
		}
		@Override
		public void onGetCommentList(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{comment:"+data+"}","comment");
			for (HashMap<String, String> map : lArrData) {
				map.put("userscreen_name", map.get("username"));
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETCOMMENTLIST_SUCCESS, lArrData);
		}
		@Override
		public void onGetRepostsList(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{reposts:"+data+"}","reposts");
			for (HashMap<String, String> map : lArrData) {
				map.put("userscreen_name", map.get("username"));
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETREPOSTLIST_SUCCESS, lArrData);
		}
		public void onGetAccountInfo(int id, String data) {
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{user:["+data+"]}","user");
			lArrData.get(0).put("avatar_large", lArrData.get(0).get("profile_image_url"));
			sendMsg(handlerMap.get(id), Constants.MSG_GETUSERINFO_SUCCESS, lArrData);
		};
		/*public void onGetAccountInfoError(int id, String err) {
			Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
		};*/
		public void onGetTimeline(int id, String data) {
			
			List<HashMap<String, String>> lArrData = NetJsonAnalyzer.JsonToHasArr("{status:"+data+"}","status");
			 for (HashMap<String, String> map : lArrData) {
				 map.put("userscreen_name",map.get("username"));
	               map.put("reposts_count",map.get("retweet_count"));
	               map.put("attitudes_count","0");
	               if(!map.get("root_in_reply_to_status_id").equals("null"))
	               {
	            	   map.put("retweeted_statustext",map.get("root_in_reply_to_status_text"));
	                   map.put("retweeted_statusid",map.get("root_in_reply_to_status_id"));
	                   map.put("retweeted_statususerscreen_name",map.get("root_in_reply_to_user_name"));
	               }
	               if(map.get("source").indexOf("</a>")==-1)
	               {
	            	   map.put("source", "<a>"+map.get("source")+"</a>");
	               }
                   if(map.get("photoUrl")!=null)
	               map.put("images", map.get("photoUrl"));
                   else
                	   map.put("images","");
                   map.put("retweeted_statusimages", "");
			}
			sendMsg(handlerMap.get(id), Constants.MSG_GETTIMELINE_SUCCESS, lArrData);
		};
		public void onGetPublic(int id, String data) {
			onGetTimeline(id, data);
		};
		/*public void onGetTimelineError(int id, String err) {
			Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
		};
		public void onSendblog(int id, String data) {
			content.setText(data);
		};
		public void onSendblogError(int id, String err) {
			Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
		};
		
		public void onGetPublicError(int id, String err) {
			Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
		};*/
	};
	static
	{
		CallBackManager.addListener(callback);
		handlerMap =new HashMap<Integer, Handler>();
	}
	//判断是否关注某人
	public static boolean  followed(String uid)
	{
	 Boolean rs=Boolean.valueOf(false);
	 int id = NeteaseApi.getInstance().doFollowed(uid);
	 judgeMap.put(id, rs);
	 synchronized (rs) {
		try {
			rs.wait();
			return rs;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	 return false;
	}
	 //获取单条微博资料
	public static void  getOneWeibo(String weiboId,final Handler handler)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		int id=NeteaseApi.getInstance().doGetOneWeibo(weiboId);
		handlerMap.put(id, handler);
		id=NeteaseApi.getInstance().doGetCommentList(weiboId);
		handlerMap.put(id, handler);
		id=NeteaseApi.getInstance().doGetRepostsList(weiboId);
		handlerMap.put(id, handler);
	}
	 //获取userline
		public static void  getUserline(String uid,String screen_name,final Handler handler,String maxId,int count)
		{
			if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
				return;
			if(uid==null)
				uid="";
			int id=NeteaseApi.getInstance().doGetUserTimeline(uid,screen_name,maxId,count);
			handlerMap.put(id, handler);
		}

	// 获取userinfo
	public static void getUserInfo(String uid,String screen_name, final Handler handler) {
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		if(uid==null)
			uid="0";
		int id = NeteaseApi.getInstance().doGetAccountInfo(uid,screen_name);
		handlerMap.put(id, handler);
	}
	// 关注用户
			public static void follow(String uid, final Handler handler) {
				
				int id = NeteaseApi.getInstance().doFollow(uid);
				handlerMap.put(id, handler);
			}
     // 关注用户
		  public static void cancelFollow(String uid, final Handler handler) {
				int id = NeteaseApi.getInstance().doCancelFollow(uid);
			handlerMap.put(id, handler);
						}			
	// 获取关注列表
		public static void getFollowList(String uid,String screen_name,int cursor, final Handler handler) {
			if(uid==null)
				uid="0";
			int id = NeteaseApi.getInstance().doGetFollowList(uid, screen_name, cursor);
			handlerMap.put(id, handler);
		}
		// 获取粉丝列表
				public static void getFollowers(String uid,String screen_name,int cursor, final Handler handler) {
					if(uid==null)
						uid="0";
					int id = NeteaseApi.getInstance().doGetFollowers(uid, screen_name, cursor);
					handlerMap.put(id, handler);
				}
	//发表微博
	public static void sendWeibo(String content)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		NeteaseApi.getInstance().doSendblog(content);
	}
	//评论一条微博
	public static void comment(String content,String id ,String is_retweet,Handler handler)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		int rId = NeteaseApi.getInstance().doComment(content, id, is_retweet);
		handlerMap.put(rId, handler);
	}
	//转发一条微博
		public static void repost(String content,String id ,String is_comment,Handler handler)
		{
			if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
				return;
			int rId = NeteaseApi.getInstance().doRepost(content, id, is_comment);
			handlerMap.put(rId, handler);
		}
	//获取朋友时间线
	public static void  getFriendline(final Handler handler,String maxId,int count)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		Integer id=NeteaseApi.getInstance().doGetTimeline(maxId,count);

		handlerMap.put(id, handler);
	}
	//获取评论我的
		public static void  getCommentToMe(final Handler handler,String maxId,int count)
		{
			if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
				return;
			Integer id=NeteaseApi.getInstance().doGetCommentToMe(maxId,count);

			handlerMap.put(id, handler);
		}
	//评论微博
	public static void comment(final Context context,String reId,String content)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		WeiboAPI api =new WeiboAPI(new AccountModel(GlobalVar.QQToken));
		api.commentWeibo(context, reId, content, "json", 0, 0, 1, 0, new HttpCallback() {
			
			@Override
			public void onResult(Object object) {
				ModelResult result =(ModelResult)object;
				if(result.isSuccess())
				{
					Toast.makeText(context, "评论成功", 1000).show();
				}
				else
				{
					Toast.makeText(context, "评论失败", 1000).show();
				}
				
			}
		}, null, 4);
	}
	//获取@我的
	public static void getMentionLine(Handler handler,String maxId,int count)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		int id = NeteaseApi.getInstance().doGetMentionLine(maxId,count);
		handlerMap.put(id, handler);
	}
	//获取公共line
		public static void getPubLine(Handler handler,String maxId,int count)
		{
			if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
				return;
			int id = NeteaseApi.getInstance().doGetPublicBlog(maxId,count);
			handlerMap.put(id, handler);
		}
	//转发微博
	public static void repost(final Context context,String reId,String content)
	{
		if(!GlobalVar.enWhich.equals("all")&&!GlobalVar.enWhich.equals("netease"))
			return;
		WeiboAPI api =new WeiboAPI(new AccountModel(GlobalVar.QQToken));
		api.repostWeibo(context, reId, content, "json", 0, 0, 1, 0, new HttpCallback() {
			
			@Override
			public void onResult(Object object) {
				ModelResult result =(ModelResult)object;
				if(result.isSuccess())
				{
					Toast.makeText(context, "转发成功", 1000).show();
				}
				else
				{
					Toast.makeText(context, "转发失败", 1000).show();
				}
				
			}
		}, null, 4);
	}
	public static  void sendMsg(Handler handler,int msgType,Object obj)
 	{
 		    Message  msg =new Message();
			msg.what=msgType;
			msg.obj=obj;
			handler.sendMessage(msg);
 	}
	
}
